package cn.edu.swu.ws.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    // 简单的用户数据库（实际项目中应该使用真实数据库）
    private static final String VALID_USERNAME = "lyt";
    private static final String VALID_PASSWORD = "123456";

    // 验证码有效期（5分钟）
    private static final long CAPTCHA_EXPIRE_TIME = 5 * 60 * 1000;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String captcha = request.getParameter("captcha");

        PrintWriter out = response.getWriter();

        try {
            // 验证验证码
            if (!validateCaptcha(request, captcha)) {
                out.write("{\"success\": false, \"message\": \"验证码错误或已过期\"}");
                return;
            }

            // 在登录成功后的部分修改：
            if (VALID_USERNAME.equals(username) && VALID_PASSWORD.equals(password)) {
                // 登录成功
                HttpSession session = request.getSession();
                session.setAttribute("user", username);
                session.setAttribute("loginTime", System.currentTimeMillis());

                // 清除验证码
                session.removeAttribute("captchaCode");
                session.removeAttribute("captchaTime");

                System.out.println("✅ 用户 " + username + " 登录成功");

                // 检查是否有原始请求路径
                String originalRequest = (String) session.getAttribute("originalRequest");
                String redirectPath = "./books"; // 默认跳转到图书列表

                if (originalRequest != null && !originalRequest.isEmpty()) {
                    redirectPath = "." + originalRequest;
                    session.removeAttribute("originalRequest");
                    System.out.println("🔄 登录后跳转到原始请求: " + redirectPath);
                }

                // 返回跳转路径
                out.write("{\"success\": true, \"message\": \"登录成功\", \"redirect\": \"" + redirectPath + "\"}");
            }

        } catch (Exception e) {
            System.out.println("❌ 登录系统错误: " + e.getMessage());
            out.write("{\"success\": false, \"message\": \"系统错误，请重试\"}");
            e.printStackTrace();
        }
    }

    private boolean validateCaptcha(HttpServletRequest request, String inputCaptcha) {
        if (inputCaptcha == null || inputCaptcha.trim().isEmpty()) {
            return false;
        }

        HttpSession session = request.getSession();
        String sessionCaptcha = (String) session.getAttribute("captchaCode");
        Long captchaTime = (Long) session.getAttribute("captchaTime");

        // 检查验证码是否存在和是否过期
        if (sessionCaptcha == null || captchaTime == null) {
            return false;
        }

        if (System.currentTimeMillis() - captchaTime > CAPTCHA_EXPIRE_TIME) {
            // 清除过期的验证码
            session.removeAttribute("captchaCode");
            session.removeAttribute("captchaTime");
            return false;
        }

        // 验证码不区分大小写
        return sessionCaptcha.equalsIgnoreCase(inputCaptcha.trim());
    }
}